module pub
{
	export class SignalManager 
	{

		private static _instance:pub.SignalManager;
		//一个消息对应一个数组列表
		public signalDic:Object;

		public constructor() 
		{
            
		}

		public static get instance():pub.SignalManager
		{
			if(!this._instance) 
			{
				this._instance=new pub.SignalManager();
			}
			return this._instance;
		}
        //注册消息
		public addSignal(signalName:string,callBack:Function,listener:any,isOnce:boolean=false):void
		{
             if(!this.signalDic) this.signalDic={};
			 var obj:Object={"listener":listener,"callBack":callBack,"isOnce":isOnce};
			 if(!this.signalDic[signalName]) this.signalDic[signalName]=[];
			 this.signalDic[signalName].push(obj);
		}
        //移除消息
		public removeSignal(signalName:string,callBack:Function,listener:any):void
		{
             if(!this.signalDic) return;
			 if(!this.signalDic[signalName]) return;
			 var objs:Array<any>=this.signalDic[signalName];
			 if(objs.length==0) return;
			 for(var i:number=objs.length-1;i>=0;i--)
			 {
				 var item:Object=<Object>(objs[i]);
				 var itemCallBack:Function=item["callBack"];
			     var itemListener:any=item["listener"];
				 if(itemCallBack!=callBack||itemListener!=listener) continue;
				 objs.splice(i,1);
				 break;
			 }
			//if(objs.length==0) delete this.signalDic[signalName];
		}
        //发送消息
		public dispatchSignal(signalName:string,param:Array<any>=null):void
		{
             if(!this.signalDic) return;
			 if(!this.signalDic[signalName]) return;
			 var objs:Array<any>=this.signalDic[signalName]; 
			 if(objs.length==0) return;
			 for(var i:number=objs.length-1;i>=0;i--)
			 {
				 var item:Object=<Object>(objs[i]);
				 var callBack:Function=item["callBack"];
			     var listener:any=item["listener"];
                //  var param:Array<any>=item["param"];
			     var isOnce:boolean=item["isOnce"];
			     if(listener){
					 if(param) callBack.apply(listener,param);
					 else callBack.apply(listener);
				 } 
				 if(isOnce) objs.splice(i,1);
			 }
			 if(objs.length==0) delete this.signalDic[signalName];
		}
        //移除所有消息
		public removeAllSignal():void
		{
            for(var i in this.signalDic)
			{
                delete this.signalDic[i];
			}
			this.signalDic=null;
		}
	}
}